package org.moon.framework.autoconfigure.springmvc;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.MoonConstants;
import org.moon.framework.autoconfigure.utils.Func;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 给请求增加RequestId
 * @author moon
 */
@Slf4j
@RequiredArgsConstructor
public class PreRequestFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String traceId = request.getHeader(MoonConstants.HEADER_REQUEST_ID);
        if(Func.isEmpty(traceId)){
            traceId = Func.getLowerUUID();
        }
        MDC.put(MoonConstants.LOG_TRACE_ID, traceId);
        filterChain.doFilter(request, response);
    }
}